package generate

import (
	"errors"
	"fmt"

	"gitee.com/miajio/go-generator-mysql/pkg/common"
	"gitee.com/miajio/go-generator-mysql/pkg/db"
)

type generatorEngineImpl struct {
	hump      bool           // 是否驼峰
	tableName string         // 表名
	columns   []db.DescTable // 字段列表
}

type generatorEngine interface {
	GeneratorStruct(tableName, host, user, pwd string, port int, dbbase, charset string) error
	GeneratorMapper()
	Hump(hump bool)
	SetTable(tableName string) error
}

func GeneratorEngine(host, user, pwd string, port int, dbbase, charset string) *generatorEngineImpl {
	db.LinkText = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True", user, pwd, host, port, dbbase, charset)
	return &generatorEngineImpl{}
}

const (
	temp = "struct %s type (\n%s)"
)

// GeneratorStruct 生成结构体方法
// tableName 表名
// host 数据库地址
// user 用户名
// pwd 密码
// port 端口号
// dbbase 数据库名
// charset 字符集
func (g *generatorEngineImpl) GeneratorStruct() (string, error) {
	if g.tableName == "" {
		return "", errors.New("table name is empty")
	}
	structName := ""
	if g.hump {
		structName = common.StringUtil.Hump(g.tableName, true)
	} else {
		structName = common.StringUtil.UpInitials(g.tableName)
	}

	params := ""

	for i := range g.columns {
		column := g.columns[i]
		params += "    " + column.RowToColumn(g.hump).ToStructColumn() + "\n"
	}

	return fmt.Sprintf(temp, structName, params), nil
}

func (g *generatorEngineImpl) GeneratorMapper() (string, error) {
	if g.tableName == "" {
		return "", errors.New("table name is empty")
	}

	result := ""

	for i := range g.columns {
		column := g.columns[i]
		column.RowToColumn(g.hump)
	}

	return result, nil
}

func (g *generatorEngineImpl) Hump() {
	g.hump = true
}

func (g *generatorEngineImpl) SetTable(tableName string) error {
	g.tableName = tableName
	columns, err := db.DescTableFunc(tableName)
	if err != nil {
		return err
	}
	g.columns = columns
	return nil
}
